<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="450px" :title="`个人信息`">
    <el-descriptions :column="1" title="用户信息" border>
      <el-descriptions-item width="300" label="用户账号">{{ userInfo.username }}</el-descriptions-item>
      <el-descriptions-item width="300" label="所在部门">{{ userInfo.departmentName }}</el-descriptions-item>
      <el-descriptions-item width="300" label="用户角色">
        <el-tag v-if="userInfo.userRole === 0">管理员</el-tag>
        <el-tag v-if="userInfo.userRole === 1">客服中心</el-tag>
        <el-tag v-if="userInfo.userRole === 2">调度中心</el-tag>
        <el-tag v-if="userInfo.userRole === 3">中心库房</el-tag>
        <el-tag v-if="userInfo.userRole === 4">分站库房</el-tag>
        <el-tag v-if="userInfo.userRole === 5">分站</el-tag>
        <el-tag v-if="userInfo.userRole === 6">配送中心</el-tag>
        <el-tag v-if="userInfo.userRole === 7">财务部</el-tag>
        <el-tag v-if="userInfo.userRole === 8">配送员</el-tag>
      </el-descriptions-item>
      <el-descriptions-item width="300" label="创建时间">{{ userInfo.createTime }}</el-descriptions-item>
    </el-descriptions>
    <p></p>
    <el-form ref="ruleFormRef" label-width="100px" label-suffix=" :" :rules="rules" :model="userInfo">
      <el-form-item label="用户头像" prop="avatar">
        <UploadImg v-model:image-url="userInfo.userAvatar" width="135px" height="135px" :file-size="3">
          <template #empty>
            <el-icon><Avatar /></el-icon>
            <span>请上传头像</span>
          </template>
          <template #tip> 头像大小不能超过 3M </template>
        </UploadImg>
      </el-form-item>
      <el-form-item label="头像选择">
        <el-button @click="changeAvatar" type="primary">随机头像</el-button>
      </el-form-item>
      <p></p>
      <el-form-item label="用户姓名" prop="name">
        <el-input v-model="userInfo.name" placeholder="请填写用户姓名" clearable></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="userGender">
        <el-select v-model="userInfo.userGender" placeholder="请选择性别" clearable>
          <el-option v-for="item in genderType" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="身份证号" prop="userIdentity">
        <el-input v-model="userInfo.userIdentity" placeholder="请填写身份证号" clearable></el-input>
      </el-form-item>
      <el-form-item label="电话号" prop="userPhone">
        <el-input v-model="userInfo.userPhone" placeholder="请填写电话号" clearable></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="UserDrawer">
import { ref, reactive, onMounted } from "vue";
import { genderType } from "@/utils/serviceDict";
import { ElMessage, FormInstance } from "element-plus";
import { User } from "@/api/interface";
import UploadImg from "@/components/Upload/Img.vue";
import { getUserInfo, editUser } from "@/api/modules/user";
import { useUserStore } from "@/stores/modules/user";
import { imageLinks } from "@/utils/avatarLinks";

const userStore = useUserStore();

onMounted(() => {});

// 用户信息
const userInfo = ref<Partial<User.ResUserList>>({});

const rules = reactive({
  name: [
    { required: true, message: "请填写用户姓名" },
    { pattern: /^[\u4e00-\u9fa5]{2,4}$/, message: "姓名格式不正确" }
  ],
  userGender: [{ required: true, message: "请选择性别" }],
  username: [
    { required: true, message: "请填写用户账号" },
    { min: 4, max: 20, message: "账号长度为4到20个字符" }
  ],
  userIdentity: [
    { required: true, message: "请填写身份证号" },
    { pattern: /^\d{17}[\dXx]$/, message: "身份证号格式不正确" }
  ],
  userRole: [{ required: true, message: "请选择用户身份" }],
  userPhone: [
    { required: true, message: "请填写电话号" },
    { pattern: /^1[3-9]\d{9}$/, message: "电话号格式不正确" }
  ]
});

const drawerVisible = ref(false);

const openDialog = async () => {
  drawerVisible.value = true;
  try {
    const response = await getUserInfo({ userId: userStore.userInfo.userId ?? 0 });
    userInfo.value = response.data;
  } catch (error) {
    console.error(error);
  }
};

const changeAvatar = () => {
  //随机选取一个头像
  userInfo.value.userAvatar = imageLinks[Math.floor(Math.random() * imageLinks.length)];
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      await editUser(userInfo.value);
      drawerVisible.value = false;
      ElMessage.success({ message: `个人信息修改成功` });
      userStore.userInfo.userAvatar = userInfo.value.userAvatar ?? "";
      userStore.userInfo.name = userInfo.value.name ?? "";
      userStore.userInfo.departmentName = userInfo.value.departmentName ?? "";
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  openDialog
});
</script>
